package common;



import java.util.Date; 
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import models.Episode;
import models.Serie;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import play.libs.WS;
import play.libs.WS.HttpResponse;
import play.libs.WS.WSRequest;
import play.libs.XPath;



public class TVRageRequest {
	
	public static long getTVRageID(String name) {
		
		long id;
		
		WSRequest request = WS.url("http://services.tvrage.com/feeds/search.php?show=" + name);
		
		HttpResponse response = null;
	    
	    try {
	    	response = request.get();
	    }
	    catch (Exception exc) {
	        System.err.println("error in tvrage json");
	    }


	    if (response.getStatus() != 200) {
	    	return 0;
	    }
	    
	    Document dom = response.getXml();
	    
	    String asd = XPath.selectText("//showid", dom);
	    id = Long.valueOf(asd);
		
		return id;
		
	}

	public static void fillSeries(Serie series) {

		WSRequest request = WS.url("http://services.tvrage.com/feeds/search.php?show=" + series.getName());
		
		HttpResponse response = null;
	    
	    try {
	    	response = request.get();
	    }
	    catch (Exception exc) {
	        System.err.println("error in tvrage xml");
	    }


	    if (response.getStatus() != 200) {
	    	return;
	    }
	    
	    Document dom = response.getXml();
	    
	    String s = XPath.selectText("//showid", dom);
	    series.setTvrageid(Long.valueOf(s));
	    
	    
	    series.save();
	    
	    
	    request = WS.url("http://services.tvrage.com/feeds/full_show_info.php?sid=" + series.getTvrageid());
		
		response = null;
	    
	    try {
	    	response = request.get();
	    }
	    catch (Exception exc) {
	        System.err.println("error in tvrage xml");
	    }


	    if (response.getStatus() != 200) {
	    	return;
	    }
	    
	    dom = response.getXml();
	    
	    
	    String image = XPath.selectText("//image", dom);
	    series.setPoster(image);
	    
	    List<Node> seasons = XPath.selectNodes("//Season", dom);
	    
	    
	    for (Node season: seasons) {
	    	
	    	Integer seasonnum = null;
	    	
	    	try {
	    		seasonnum = Integer.valueOf(season.getAttributes().item(0).getNodeValue());
		    }
		    catch (NullPointerException n) {}
		    catch (NumberFormatException ne) {}
	    	
	    	for (int i=0; i<season.getChildNodes().getLength(); i++ ) {
	    		
	    		Node episode = season.getChildNodes().item(i);
	    		
	    		Integer episode_absolute = null;
	    		
	    		try {    		
	    			episode_absolute = Integer.valueOf(XPath.selectText("epnum", episode));
	    		}
		    	catch (NullPointerException n) {}
		    	catch (NumberFormatException ne) {}
	    		
	    		
	    		Integer episode_relative = null;
	    		
	    		try {    		
	    			episode_relative = Integer.valueOf(XPath.selectText("seasonnum", episode));
	    		}
		    	catch (NullPointerException n) {}
		    	catch (NumberFormatException ne) {}
	    		
	    		if (episode_relative == null)
	    			continue;
	    		
	    		String airdate = XPath.selectText("airdate", episode);
	    		
	    		Date air_date = null;

	    		try {
					air_date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(airdate);
				} 
	    		catch (ParseException e) {}
	    		catch (NullPointerException n) {}
	    		
	    		String epimage = XPath.selectText("screencap", episode);
	    		
	    		if (epimage == null) 
	    			epimage = series.getPoster();
	    		
	    		String title = XPath.selectText("title", episode);
	    		
	    		Episode newEpisode = new Episode(seasonnum, episode_relative, episode_absolute, title, null,
	    				epimage, air_date, null, series);
	    		
	    		series.addEpisode(newEpisode);
	    	}
	    	
	    }
	    

	    series.save();
		
	}

	public static Serie getSerie(long tvrageid) {
		
		WSRequest request = WS.url("http://services.tvrage.com/feeds/full_show_info.php?sid=" + tvrageid);
		
		HttpResponse response = null;
	    
	    try {
	    	response = request.get();
	    }
	    catch (Exception exc) {
	        System.err.println("error in tvrage xml");
	    }


	    if (response.getStatus() != 200) {
	    	return null;
	    }
	    
	    Document dom = response.getXml();
	    
	    
	    
	    String name = null;
	    
	    try {
	    	name = XPath.selectText("//name", dom);
	    }
	    catch (NullPointerException n) {}
	    
	    
	    Integer runtime = null;
	    
	    try {
	    	runtime = Integer.valueOf(XPath.selectText("//runtime", dom));
	    }
	    catch (NullPointerException n) {}
	    catch (NumberFormatException ne) {}
	    
	    
	    String channel = null;
	    
	    try {
	    	channel = XPath.selectText("//network", dom);
	    }
	    catch (NullPointerException n) {}
	    
	    
	    DateFormat timeFormatter = new SimpleDateFormat("mm:ss");
	    
	    Date airTime = null;

		try {
			airTime = timeFormatter.parse(XPath.selectText("//airtime", dom));
		} 	catch (ParseException e1) {}
			catch (NullPointerException n) {}

	    
	    
	    String airDay = null;
	    
	    try {
	    	airDay = XPath.selectText("//airday", dom);
	    }
	    catch (NullPointerException n) {}
	    
	    
	    String timezone = null;
	    
	    try {
	    	timezone = XPath.selectText("//timezone", dom);
	    }
	    catch (NullPointerException n) {}
	    
	    
	    String poster = null;
	    
	    try {
	    	poster = XPath.selectText("//image", dom);
	    }
	    catch (NullPointerException n) {}
	    
	    
	    String country = null;
	    
	    try {
	    	country = XPath.selectText("//origin_country", dom);
	    }
	    catch (NullPointerException n) {}
	    
	    
	    String startDate = null;
	    
		try {
			startDate = XPath.selectText("//started", dom);
		}
		catch (NullPointerException n) {}
	    
		
		String endDate = null;
	    
		try {
			endDate = XPath.selectText("//ended", dom);
		}
		catch (NullPointerException n) {}
	    
		
		List<Node> genreNodes = null;
		try {
			genreNodes = XPath.selectNodes("//genre", dom);
		}
	    catch (NullPointerException n) {}
	    
	    
	    List<String> genres = new ArrayList<String>();
	    
	    for (Node genre : genreNodes) {
	    	String newGenre = genre.getTextContent();
	    	genres.add(newGenre);
	    }
	    

	    
	    
	    
	    Serie newSerie = new Serie(name, runtime, channel, airTime, airDay, timezone, null, poster, country, startDate, endDate, tvrageid, null, null, null, genres);
	    
	    newSerie.save();
	    
	    List<Node> seasons = XPath.selectNodes("//Season", dom);
	    
	    
	    for (Node season: seasons) {
	    	
	    	Integer seasonnum = null;
	    	
	    	try {
	    		seasonnum = Integer.valueOf(season.getAttributes().item(0).getNodeValue());
		    }
		    catch (NullPointerException n) {}
		    catch (NumberFormatException ne) {}
	    	
	    	for (int i=0; i<season.getChildNodes().getLength(); i++ ) {
	    		
	    		Node episode = season.getChildNodes().item(i);
	    		
	    		Integer episode_absolute = null;
	    		
	    		try {    		
	    			episode_absolute = Integer.valueOf(XPath.selectText("epnum", episode));
	    		}
		    	catch (NullPointerException n) {}
		    	catch (NumberFormatException ne) {}
	    		
	    		
	    		Integer episode_relative = null;
	    		
	    		try {    		
	    			episode_relative = Integer.valueOf(XPath.selectText("seasonnum", episode));
	    		}
		    	catch (NullPointerException n) {}
		    	catch (NumberFormatException ne) {}
	    		
	    		if (episode_relative == null)
	    			continue;
	    		
	    		String airdate = XPath.selectText("airdate", episode);
	    		
	    		Date air_date = null;

	    		try {
					air_date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(airdate);
				} 
	    		catch (ParseException e) {}
	    		catch (NullPointerException n) {}
	    		
	    		String epimage = XPath.selectText("screencap", episode);
	    		
	    		if (epimage == null) 
	    			epimage = poster;
	    		
	    		String title = XPath.selectText("title", episode);
	    		
	    		Episode newEpisode = new Episode(seasonnum, episode_relative, episode_absolute, title, null,
	    				epimage, air_date, null, newSerie);
	    		
    		
	    		newSerie.addEpisode(newEpisode);
	    	}
	    	
	    }

	    newSerie.save();

	    iMDBRequest.fillSeries(newSerie);
		
		
		return newSerie;
	}
	
	
	public static void updateSerie(Serie s) {
		
		WSRequest request = WS.url("http://services.tvrage.com/feeds/full_show_info.php?sid=" + s.getTvrageid());
		
		HttpResponse response = null;
	    
	    try {
	    	response = request.get();
	    }
	    catch (Exception exc) {
	        System.err.println("error in tvrage xml");
	    }


	    if (response.getStatus() != 200) {
	    	return;
	    }
	    
	    
	    Document dom = response.getXml();
	    
	    
	    
	    DateFormat timeFormatter = new SimpleDateFormat("mm:ss");
	    
	    
	    Date airTime = null;

		try {
			airTime = timeFormatter.parse(XPath.selectText("//airtime", dom));
		} 	catch (ParseException e1) {}
			catch (NullPointerException n) {}

		if (airTime != null) {
			s.setAirTime(airTime);
		}
	    
	    
	    String airDay = null;
	    
	    try {
	    	airDay = XPath.selectText("//airday", dom);
	    }
	    catch (NullPointerException n) {}
	    
	    if (airDay != null) {
			s.setAirDay(airDay);
		}
	    
	    
	    String timezone = null;
	    
	    try {
	    	timezone = XPath.selectText("//timezone", dom);
	    }
	    catch (NullPointerException n) {}
	    
	    if (timezone != null) {
			s.setTimezone(timezone);
		}
	    
	    
	    String poster = null;
	    
	    try {
	    	poster = XPath.selectText("//image", dom);
	    }
	    catch (NullPointerException n) {}
	    
	    if (poster != null) {
			s.setPoster(poster);
		}
	    
	    
		String endDate = null;
	    
		try {
			endDate = XPath.selectText("//ended", dom);
		}
		catch (NullPointerException n) {}
		
		if (endDate != null) {
			s.setEndDate(endDate);
		}
		
		
	    
		s.save();
		
		
	    
	    List<Node> seasons = XPath.selectNodes("//Season", dom);
	    
	    
	    for (Node season: seasons) {
	    	
	    	Integer seasonnum = null;
	    	
	    	try {
	    		seasonnum = Integer.valueOf(season.getAttributes().item(0).getNodeValue());
		    }
		    catch (NullPointerException n) {}
		    catch (NumberFormatException ne) {}
	    	
	    	for (int i=0; i<season.getChildNodes().getLength(); i++ ) {
	    		
	    		Node episode = season.getChildNodes().item(i);
	    		
	    		Integer episode_absolute = null;
	    		
	    		try {    		
	    			episode_absolute = Integer.valueOf(XPath.selectText("epnum", episode));
	    		}
		    	catch (NullPointerException n) {}
		    	catch (NumberFormatException ne) {}
	    		
	    		Episode ep = null;
	    		
	    		if (episode_absolute != null)
	    			 ep = Episode.getEpisode(s, episode_absolute);
	    		
	    		if (ep == null) {
	    			
	    			Integer episode_relative = null;
		    		
		    		try {    		
		    			episode_relative = Integer.valueOf(XPath.selectText("seasonnum", episode));
		    		}
			    	catch (NullPointerException n) {}
			    	catch (NumberFormatException ne) {}
		    		
		    		if (episode_relative == null)
		    			continue;
		    		
		    		String airdate = XPath.selectText("airdate", episode);
		    		
		    		Date air_date = null;

		    		try {
						air_date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(airdate);
					} 
		    		catch (ParseException e) {}
		    		catch (NullPointerException n) {}
		    		
		    		String epimage = XPath.selectText("screencap", episode);
		    		
		    		if (epimage == null) 
		    			epimage = poster;
		    		
		    		String title = XPath.selectText("title", episode);
		    		
		    		Episode newEpisode = new Episode(seasonnum, episode_relative, episode_absolute, title, null,
		    				epimage, air_date, null, s);
		    		
	    		
		    		s.addEpisode(newEpisode);
	    			
	    		}
	    		
	    		else {
	    			
	    			String epimage = XPath.selectText("screencap", episode);
		    		
		    		if (epimage != null) 
		    			ep.setImage(epimage);
		    		
		    		String title = XPath.selectText("title", episode);
		    		
		    		if (title != null) 
		    			ep.setTitle(title);
		    		
		    		ep.save();
	    			
	    		}
	    		
	    		
	    	}
	    	
	    }

	    s.save();
		
	}

}
